import { useCallback, useEffect, useState } from 'react';
import { Input, Tabs, Card, Empty, Spin, Tag } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { getArticleListByCategory } from '@/api/article';
import { Typography } from 'antd';
import 'github-markdown-css/github-markdown.css';
const { Paragraph } = Typography;

interface Article {
  id: number;
  title: string;
  content: string;
  manager_id: number;
  manager_name: string;
  tags: string[];
  category: 'edible' | 'poisonous' | 'medicinal';
  color: string;
  created_time: string;
}

interface CategoryData {
  list: Article[];
  loading: boolean;
  total: number;
}

/**
 * 文章分类
 */
const Categories = () => {
  const [searchText, setSearchText] = useState('');
  const [searchParams] = useSearchParams();
  const category = searchParams.get('category');
  const navigate = useNavigate();

  // 为每个分类维护独立的状态
  const [categoryData, setCategoryData] = useState<Record<string, CategoryData>>({
    edible: { list: [], loading: false, total: 0 },
    poisonous: { list: [], loading: false, total: 0 },
    medicinal: { list: [], loading: false, total: 0 },
  });

  // 获取指定分类的文章列表
  const fetchCategoryArticles = useCallback(
    async (category: 'edible' | 'poisonous' | 'medicinal') => {
      try {
        setCategoryData((prev) => ({
          ...prev,
          [category]: { ...prev[category], loading: true },
        }));

        const res = await getArticleListByCategory({
          category,
          page: 1,
          limit: 10,
          keyword: searchText,
        });
        setCategoryData((prev) => ({
          ...prev,
          [category]: {
            list: res.data.list,
            loading: false,
            total: res.data.total,
          },
        }));
      } catch {
        setCategoryData((prev) => ({
          ...prev,
          [category]: { ...prev[category], loading: false },
        }));
      }
    },
    [searchText]
  );

  // 监听搜索文本变化，延迟执行搜索
  useEffect(() => {
    const timer = setTimeout(() => {
      const currentCategory = (category || 'edible') as 'edible' | 'poisonous' | 'medicinal';
      // 只在搜索文本变化或组件初始化时发送请求
      if (searchText || !categoryData[currentCategory].list.length) {
        fetchCategoryArticles(currentCategory);
      }
    }, 300);

    return () => clearTimeout(timer);
  }, [category, categoryData, fetchCategoryArticles, searchText]);

  // 切换标签时加载对应分类数据
  const handleTabChange = (activeKey: string) => {
    navigate(`/categories?category=${activeKey}`);
    // 移除这里的请求，因为 useEffect 会处理数据加载
  };

  // 渲染文章卡片
  const renderArticleCard = (article: Article) => {
    const tags = article.tags;
    return (
      <Card
        key={article.id}
        hoverable
        className="mb-4 overflow-hidden hover:shadow-lg transition-shadow duration-300"
        style={{ margin: '0 16px 16px 16px' }}
      >
        <div className="flex space-x-4">
          <div className="flex-1">
            <div className="flex justify-between items-start mb-2">
              <h3 className="text-lg font-medium text-gray-800">{article.title}</h3>
              <div className="space-x-1">
                {tags?.map((tag, index) => (
                  <Tag
                    key={index}
                    color={
                      article.category === 'poisonous'
                        ? 'red'
                        : article.category === 'medicinal'
                        ? 'blue'
                        : 'green'
                    }
                  >
                    {tag}
                  </Tag>
                ))}
                <Tag color="default">{article.color}</Tag>
              </div>
            </div>
            <Paragraph ellipsis={{ rows: 4 }}>
              <span className="text-gray-600 text-sm mb-4 line-clamp-2">{article.content}</span>
            </Paragraph>
            <div className="flex justify-between items-center">
              <span
                className="text-emerald-600 hover:text-emerald-700 cursor-pointer"
                onClick={() => navigate(`/categories/${article.id}?category=${article.category}`)}
              >
                查看详情 →
              </span>
              <div className="text-gray-500 text-sm">
                <span>作者：{article.manager_name}</span>
                <span className="ml-4">{new Date(article.created_time).toLocaleDateString()}</span>
              </div>
            </div>
          </div>
        </div>
      </Card>
    );
  };

  const items = [
    {
      key: 'edible',
      label: '可食用类',
      children: (
        <Spin spinning={categoryData.edible.loading}>
          {categoryData.edible.list.length > 0 ? (
            categoryData.edible.list.map(renderArticleCard)
          ) : (
            <Empty description={searchText ? '未找到相关文章' : '暂无可食用类野生菌数据'} />
          )}
        </Spin>
      ),
    },
    {
      key: 'poisonous',
      label: '有毒类',
      children: (
        <Spin spinning={categoryData.poisonous.loading}>
          {categoryData.poisonous.list.length > 0 ? (
            categoryData.poisonous.list.map(renderArticleCard)
          ) : (
            <Empty description={searchText ? '未找到相关文章' : '暂无有毒类野生菌数据'} />
          )}
        </Spin>
      ),
    },
    {
      key: 'medicinal',
      label: '药用类',
      children: (
        <Spin spinning={categoryData.medicinal.loading}>
          {categoryData.medicinal.list.length > 0 ? (
            categoryData.medicinal.list.map(renderArticleCard)
          ) : (
            <Empty description={searchText ? '未找到相关文章' : '暂无药用类野生菌数据'} />
          )}
        </Spin>
      ),
    },
  ];

  return (
    <div className="h-full bg-gray-50 py-8 px-4">
      <div className="max-w-6xl mx-auto">
        <div className="mb-8">
          <h1 className="text-2xl font-bold text-gray-800 mb-4">野生菌分类</h1>
          <Input
            size="large"
            placeholder="搜索文章标题或内容..."
            prefix={<SearchOutlined className="text-gray-400" />}
            className="max-w-lg"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            allowClear
          />
        </div>

        <Tabs
          items={items}
          defaultActiveKey={category || 'edible'}
          onChange={handleTabChange}
          centered
          className="bg-white p-6 rounded-lg shadow-md"
        />
      </div>
    </div>
  );
};

export default Categories;
